import { useStore } from '@/hooks';
import { Button, Dialog, Form, Input } from '@alifd/next';
import React, { useEffect, useRef, useState } from 'react';
import { t } from '@lingui/macro';
import DrawerFooter from '@/components/DrawerFooter';
import { FieldsGrid } from '../stores/definitions_entrance';
import { observer } from 'mobx-react-lite';
import { observable } from 'mobx';

const FromItem = Form.Item;

const formItemLayout = {
  labelCol: {
    fixedSpan: 8,
  },
  wrapperCol: {
    span: 16,
  },
  style: { marginBottom: 20 },
};

const EntranceConfig = ({ dictInfo, modal, onCancel, onSubmit }) => {
  const { xcxStore: store } = useStore();
  const editCtx = useRef({ origin: {}, changed: {} }).current; // 用于计算是否修改
  const [isViewMode] = useState(modal[0] === 'viewEntrance');
  const formProps = isViewMode ? { field: false } : {};
  const [entrance] = useState(() => observable({}));
  useEffect(() => { if (modal[1]?.startsWith?.('toClose') || modal[2]?.startsWith?.('toClose')) handleCancel(); }, [modal]);
  useEffect(() => {
    if (JSON.stringify(dictInfo) === '{}') {
      editCtx.origin = _.cloneDeep({});
      _.assign(entrance, {});
      _.set(entrance, 'disabled', false);
      _.set(entrance, 'sortWeight', 1);
    } else {
      (async () => {
        const res = dictInfo;
        editCtx.origin = _.cloneDeep(res);
        _.assign(entrance, res);
      })();
    }
  }, []);

  if (!entrance) return <></>;

  const overrideModel = {
    itemId: {
      label: t`标识`,
      ui: {
        renderer: (v) => <Input value={v} placeholder="请输入标识" readOnly={JSON.stringify(dictInfo) !== '{}'} />,
      },
    },
    name: {
      label: t`名称`,
      ui: {
        renderer: (v) => <Input value={v} placeholder="请输入名称" />,
      },
    },
  }
  /**
   * @description 动态回现表单数据
   * @param {*} values
   * @param {*} item 数据Items
   */
  const handleChange = (values, item) => {
    const { name, value } = item;
    _.set(entrance, name, value);
    // eslint-disable-next-line eqeqeq
    editCtx.changed[name] = value == _.get(editCtx.origin, name) ? undefined : value;
  };

  /**
   * @description 提交表单实现修改配置
   * @param {*} r formData
   */
  const handleSubmit = (values, errors) => {
    if (!_.isEmpty(errors)) {
      return;
    }
    onSubmit?.(entrance);
  };
  const handleCancel = () => {
    // eslint-disable-next-line no-return-assign
    if (!_.isEmpty(_.transform(editCtx.changed, (r, v, k) => v !== undefined && (r[k] = v)))) {
      Dialog.confirm({
        content: t`放弃修改内容？`,
        onOk: () => onCancel?.(),
      });
      return;
    }
    onCancel?.();
  };

  return (
    <Form
      isPreview={isViewMode}
      {...formProps}
      value={entrance}
      onChange={handleChange}
      useLabelForErrorMessage
    >
      <FieldsGrid
        formData={entrance}
        mode={isViewMode ? 'view' : 'edit'}
        columns={1}
        overrideModel={overrideModel}
        itemLayout={{ ...formItemLayout, labelAlign: 'left' }}
        fields={[
          'itemId', 'name', 'disabled', 'sortWeight',
        ]}
      />
      <DrawerFooter>
        <FromItem>
          {!isViewMode && <Form.Submit validate type="primary" onClick={handleSubmit}>{t`保存`}</Form.Submit>}
          <Button style={{ marginLeft: 8 }} onClick={handleCancel}>{t`取消`}</Button>
        </FromItem>
      </DrawerFooter>
    </Form>
  );
};
export default observer(EntranceConfig);
